package cj.com.chabaike.ui.frag;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.PauseOnScrollListener;
import com.tumblr.bookends.Bookends;
import com.viewpagerindicator.LinePageIndicator;

import java.util.ArrayList;
import java.util.List;

import butterknife.InjectView;
import cj.com.chabaike.R;
import cj.com.chabaike.bll.PandaPagerManager;
import cj.com.chabaike.bll.RWServer;
import cj.com.chabaike.dao.FetchJSONDAO;
import cj.com.chabaike.entity.CommendList;
import cj.com.chabaike.entity.EliteList;
import cj.com.chabaike.entity.HomeData;
import cj.com.chabaike.entity.NewsList;
import cj.com.chabaike.entity.Thing;
import cj.com.chabaike.ui.act.MainPager;
import cj.com.chabaike.ui.adapter.BaseRecyclerAdapter;
import cj.com.chabaike.ui.utils.BmpUtlPauseOnScrollListener;
import cj.com.chabaike.ui.utils.HttpBitMapHelp;
import cj.com.chabaike.ui.utils.Navigator;
import cj.com.chabaike.ui.view.HeaderLinearLayout;
import cj.com.chabaike.ui.view.RecyclerLoaderFooter;
import jp.co.recruit_lifestyle.android.widget.WaveSwipeRefreshLayout;

/**
 * 该碎片专门用于首页数据
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link RecyclerFragment1.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link RecyclerFragment1#newInstance} factory method to
 * create an instance of this fragment.
 */
public class RecyclerFragment1 extends Fragment implements WaveSwipeRefreshLayout.OnRefreshListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    RWServer rws;
    PandaPagerManager ppm;
    ThingRecyclerAdapter mThingRecyclerAdapter;
    static BitmapUtils bitmapUtils;
    ViewPager headerViewPager;
    List<HeaderFragment> mHeaderFragmentList;
    List<HomeData> mHomedataList;
    View footerLoadView;
    LinePageIndicator mIndicator; //头部viewpager指示器



    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;


    private RecyclerView mRecyclerView;
    private WaveSwipeRefreshLayout mWaveSwipeRefreshLayout; //这个是下拉刷新的控件
    private Bookends<ThingRecyclerAdapter> mBookends; //用于添加RecylcerView头部
    private HeaderViewPagerAdapter headerViewPagerAdapter;//头部ViewPager适配器;
    private RecyclerLoaderFooter footer; //到底加载
    //private List<Fragment> headerFragmentList;


    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment RecyclerFragment1.
     */
    // TODO: Rename and change types and number of parameters
    public static RecyclerFragment1 newInstance(String param1, String param2) {
        RecyclerFragment1 fragment = new RecyclerFragment1();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public RecyclerFragment1() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHomedataList = new ArrayList<>();

        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

        rws = RWServer.getInstance(getActivity().getApplication());
        ppm = PandaPagerManager.getPandaPagerManagerInstance();

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.mfrag1, null, false);
        footer = new RecyclerLoaderFooter(getActivity().getApplicationContext());
        bitmapUtils = HttpBitMapHelp.getBitmapUtils(getActivity().getApplicationContext());
        BitmapDisplayConfig cfg = new BitmapDisplayConfig();
        cfg.setLoadingDrawable(getResources().getDrawable(R.drawable.common_list_item_default_img));
        cfg.setLoadFailedDrawable(getResources().getDrawable(R.drawable.common_list_item_default_img));

        bitmapUtils.configDefaultDisplayConfig(cfg);


        mWaveSwipeRefreshLayout = (WaveSwipeRefreshLayout) view.findViewById(R.id.main_swipe);
        mWaveSwipeRefreshLayout.setColorSchemeColors(Color.WHITE, Color.WHITE); //设置转动圈的颜色
        mWaveSwipeRefreshLayout.setOnRefreshListener(this); //刷新监听器


        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //设置RecylerView的布局模式为垂直
        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(layoutManager);

        footerLoadView = footer.getFootView(mRecyclerView, mWaveSwipeRefreshLayout, new RecyclerLoaderFooter.IFooterBtndown() {
            @Override
            public void whileFootBtnDown() {
                doLoadMore();

            }
        });


        /******************************配置适配器******************************/
        // initmThingRecyclerAdapter();


        mThingRecyclerAdapter = new ThingRecyclerAdapter();


        // mThingRecyclerAdapter.updateList(getThings());
        mWaveSwipeRefreshLayout.setRefreshing(true);

        //  mThingRecyclerAdapter.updateList(getEliteList());
        mThingRecyclerAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<EliteList>() {
            @Override
            public void onItemClick(View view, EliteList item, boolean isLongClick) {

                if (!isLongClick) {
                   Log.w("mThingRecyclerAdapter","mThingRecyclerAdapter"+mThingRecyclerAdapter.getItemCount());
                    Navigator.launchDetail(MainPager.of(getActivity()), view, item, MainPager.of(getActivity()).fragmentBackround);
                }
                //  Toast.makeText(getActivity(),"长按？" + isLongClick,Toast.LENGTH_LONG).show();
            }
        });

        /*****************添加头部******************/
        // LayoutInflater mInflater = LayoutInflater.from(getActivity().getApplicationContext());
        // LinearLayout headerView = (LinearLayout) mInflater.inflate(R.layout.homepager_header, mRecyclerView, false);

        HeaderLinearLayout headerView = initHeaderView();
        headerView.setmWaveSwipeRefreshLayout(mWaveSwipeRefreshLayout);
        headerView.setHeaderViewPager(headerViewPager);
        mThingRecyclerAdapter.setIsAddheader(true);
        mBookends = new Bookends<>(mThingRecyclerAdapter);
        mBookends.addHeader(headerView);
        mBookends.addFooter(footerLoadView);

        //mRecyclerView.setAdapter(mThingRecyclerAdapter);
        mRecyclerView.setAdapter(mBookends);
        headerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("HeaderLinearLayout", "onTouchEvent headerViewPager   ====" + headerViewPager.getCurrentItem());
                initHeaderViewClick(v);
            }

        });
        footer.FooterBtnVisable(false);
        // mThingRecyclerAdapter.updateList(new ArrayList<EliteList>());
        getEliteList();
        return view;
    }

    /*******************onCreateView结束***********************/


    /**
     * ****************加载更多**********************
     */
    private void doLoadMore() {
        footer.FooterBtnVisable(false);
        rws.getHomeData(ppm.getHomePgerNextPager(), new FetchJSONDAO.ResultBack() {
            @Override
            public void resultWhat(boolean isSuccusful, HomeData homeData) {
                if (isSuccusful) {
                    mHomedataList.add(homeData);
                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(), "加载成功", Toast.LENGTH_SHORT).show();
                            initList();
                            footer.FooterBtnVisable(true);
                            refreshFragment();
                        }
                    });


                    PandaPagerManager.HomePagerCurrentpager++;

                } else {
                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                            footer.FooterBtnVisable(true);
                            Toast.makeText(getActivity(), "加载失败，请重试", Toast.LENGTH_SHORT).show();
                        }
                    });

                }

            }
        });


    }

    void initList() {

        List<EliteList> list = new ArrayList<>();

        for (HomeData homeData : mHomedataList) {
            list.addAll(homeData.getEliteList());
        }
        mThingRecyclerAdapter.updateList(list);
    }

    ;

    void refreshFragment() {
        mThingRecyclerAdapter.notifyDataSetChanged();
        mRecyclerView.refreshDrawableState();
        mBookends.notifyDataSetChanged();

    }

    /**
     * ***********定义头部布局**********************************
     */


    private HeaderLinearLayout initHeaderView() {
        LayoutInflater mInflater = LayoutInflater.from(getActivity().getApplicationContext());
        HeaderLinearLayout headerView = (HeaderLinearLayout) mInflater.inflate(R.layout.homepager_header, mRecyclerView, false);

        headerViewPager = (ViewPager) headerView.findViewById(R.id.homepager_header_vp);
        mIndicator= (LinePageIndicator) headerView.findViewById(R.id.header_indicator);

        initHeaderFragment();
        return headerView;
    }

    private void initHeaderViewClick(View view) {
        CommendList commendList = mHomeData.getCommendList().get(headerViewPager.getCurrentItem());
        if(commendList.getType().equals("11")){
            Navigator.launchSpecial_DetailSeach(getActivity(),view,ppm.getSpecialDetailUrl(commendList.getId()),MainPager.of(getActivity()).fragmentBackround);
        }else {
            NewsList item = new NewsList();
            item.setTitle(commendList.getTitle());
            item.setID(commendList.getId());
            Navigator.launchDetailNews(MainPager.of(getActivity()),view,item,MainPager.of(getActivity()).fragmentBackround);
        }

    }

    private void initHeaderFragment() {
        mHeaderFragmentList = getHeaderFragmentList();
        headerViewPagerAdapter = new HeaderViewPagerAdapter(getFragmentManager());

        headerViewPager.setAdapter(headerViewPagerAdapter);
        mIndicator.setViewPager(headerViewPager);

    }


    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }


    private void refresh() {
        getEliteList();

    }

    public List<HeaderFragment> getHeaderFragmentList() {
        List<CommendList> mCommendList = new ArrayList<>();
        List<HeaderFragment> tempHeaderFragmentList = new ArrayList<>();

        for (int i = 0; i < 5; i++) {
            HeaderFragment headerFragment = new HeaderFragment(new HeaderFragment.imgClick() {
                @Override
                public void whileImgClick(View v) {
                    initHeaderViewClick(v);
                }
            });
            tempHeaderFragmentList.add(headerFragment);


        }


        return tempHeaderFragmentList;
    }


    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }

    @Override
    public void onRefresh() {
        refresh();
    }

    HomeData mHomeData = null;


    List<EliteList> getEliteList() {

        rws.getHomeData(ppm.getHomePgerFirstPager(),
                new FetchJSONDAO.ResultBack() {
                    @Override
                    public void resultWhat(boolean isSuccusful, HomeData homeData) {
                        if (isSuccusful) {
                            mHomeData = homeData;
                            mHomedataList.clear();
                            mHomedataList.add(0, homeData);
                            mThingRecyclerAdapter.updateList(homeData.getEliteList());
                            refreshFragment();
                            updateHeaderFragment();

                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {

                                    mWaveSwipeRefreshLayout.setRefreshing(false);
                                    footer.FooterBtnVisable(true);
                                    Toast.makeText(getActivity(), "更新成功", Toast.LENGTH_SHORT).show();
                                }
                            }, 1000);
                        } else {

                            // mThingRecyclerAdapter.updateList(null);
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    mWaveSwipeRefreshLayout.setRefreshing(false);
                                    footer.FooterBtnVisable(true);
                                    Toast.makeText(getActivity(), "更新失败", Toast.LENGTH_SHORT).show();
                                }
                            }, 1000);
                        }

                        /*********转动圈停止转动*******/


                    }
                });


        return null;
    }

    private void updateHeaderFragment() {
        for (int i = 0; i < mHeaderFragmentList.size(); i++) {
            Log.e("更新头部frag", "第" + i + "个");
            mHeaderFragmentList.get(i).initData(mHomeData.getCommendList().get(i));
        }

    }


    /**
     * ***********************适配器区*************************
     */
    /*recylcerView的适配器 使用带有cardView的适配器 第二层继承*/

    class ThingRecyclerAdapter extends BaseRecyclerAdapter<EliteList> {

        @Override
        public ThingHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recylcer_item, parent, false);
            return new ThingHolder(view);
        }


        public class ThingHolder extends BaseRecyclerAdapter<EliteList>.ViewHolder {


            @InjectView(R.id.title)
            TextView titleTextView;

            @InjectView(R.id.ItemViewKeyWord)
            TextView keyWorldTextView;

            @InjectView(R.id.Hint)
            TextView hintTextView;

            @InjectView(R.id.ItemViewImg0)
            ImageView ItemViewImg;

            @InjectView(R.id.ItemView3imgLayout)
            LinearLayout iv3il;//含有3张图片的布局

            @InjectView(R.id.ItemViewImg1)
            ImageView ItemViewImg1;
            @InjectView(R.id.ItemViewImg2)
            ImageView ItemViewImg2;
            @InjectView(R.id.ItemViewImg3)
            ImageView ItemViewImg3;


            public ThingHolder(View itemView) {
                super(itemView);
            }

            public void populate(EliteList item) {

                titleTextView.setText(item.getTitle());
                keyWorldTextView.setText(item.getKeyWord());
                hintTextView.setText("阅读" + item.getHits());


                if (!item.getType().equals("4")) {
                    Log.w("使用的行视图", "1张图的视图");
                    iv3il.setVisibility(View.GONE);
                    ItemViewImg.setVisibility(View.VISIBLE);
                    bitmapUtils.display(ItemViewImg, item.getImgurls().toString());
                    Log.i("imgurl", item.getTitle() + item.getImgurls().toString());

                    if (bitmapUtils == null) {

                        Log.i("bitmapUtils", "bitmapUtils 为空");
                    }
                } else {

                    Log.w("使用的行视图", "三张图的视图");
                    ItemViewImg.setVisibility(View.GONE);
                    iv3il.setVisibility(View.VISIBLE);
                    List<String> ImgUrllist = rws.ImgurlArarryToList(item.getImgurls());
                    bitmapUtils.display(ItemViewImg1, ImgUrllist.get(0));
                    bitmapUtils.display(ItemViewImg2, ImgUrllist.get(1));
                    bitmapUtils.display(ItemViewImg3, ImgUrllist.get(2));
                    Log.i("imgurl", item.getTitle() + item.getImgurls().toString());


                    if (bitmapUtils == null) {

                        Log.i("bitmapUtils", "bitmapUtils 为空");
                    }
                }

            }

        }
    }


    /**
     * **************************头部的ViewPager适配器*******************************
     */

    class HeaderViewPagerAdapter extends FragmentPagerAdapter {
        FragmentManager fm;


        public HeaderViewPagerAdapter(FragmentManager fm) {
            super(fm);
            this.fm = fm;
        }

        public void updateHeaderViewPager() {
            // this.mListFragment = listFragment;
            Log.i("updateHeaderViewPager", "updateHeaderViewPager");
            notifyDataSetChanged();
        }

        @Override
        public Fragment getItem(int position) {
            return mHeaderFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mHeaderFragmentList.size();
        }
    }


    /**
     * **************************头部Fragment*********************************************
     */
    @SuppressLint("ValidFragment")
      public static class HeaderFragment extends Fragment  {
        imgClick mimgClick;
        CommendList commendList;
        Bundle bundle;
        ImageView img;
        TextView text;


        public HeaderFragment(Bundle bundle) {
            this.bundle = bundle;
        }

        public HeaderFragment() {
        }

        public HeaderFragment(imgClick mimgClick) {
            this.mimgClick = mimgClick;
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            bundle = getArguments();

            if (bundle == null) {
                bundle = savedInstanceState;
            }
            if (bundle != null) {
                commendList = (CommendList) bundle.getSerializable("commendList");
            }


            if (commendList != null) {
                Log.w("HeaderFragment获取到了", commendList.getTitle());
            } else {

                Log.w("HeaderFragment没有获取到", "真是个悲伤的通知");
            }


        }

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.homepager_header_fragment, container, false);
            img = (ImageView) view.findViewById(R.id.header_fragment_imageView);
            img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(mimgClick!=null){
                        mimgClick.whileImgClick(v);

                    }
                }

            });
            text = (TextView) view.findViewById(R.id.header_frament_text);
            initData(commendList);
            //bitmapUtils.display(img, commendList.getImgurl());
            // text.setText("6666666666666666666661");
            Log.e("onCreateView", "" + text.getText().toString());
            return view;
        }

        public void initData(CommendList mCommendList) {
            this.commendList = mCommendList;
            if (commendList != null) {
                if (img == null) {
                    Log.e("头部Frag", "img 为空");
                } else {

                    bitmapUtils.display(img, commendList.getImgurl());
                }
                if (text == null) {
                    Log.e("头部Frag", "text 为空");
                } else {

                    text.setText(commendList.getTitle());
                }

                ;
            }
            // text.setText("66666666666666666666");

        }


        @Override
        public void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);

            outState.putSerializable("commendList", commendList);


        }


        public static interface imgClick {
            public void whileImgClick(View v);

        }


    }


    public interface updateHeaderFrag {
        public void updateFrag(CommendList commendList);

    }


}
